// src/renderer/store/training.js

import { defineStore } from 'pinia'

export const useTrainingStore = defineStore('training', {
  state: () => ({
    // 当前训练状态
    isTraining: false,
    trainingStatus: '',
    trainingProgress: 0,
    currentEpoch: 0,
    trainingLoss: 0,
    
    // 训练配置
    currentConfig: {
      modelName: 'YOLOv8',
      epochs: 100,
      batchSize: 32,
      learningRate: 0.001,
      datasetPath: '',
      outputPath: ''
    },
    
    // 训练历史
    trainingHistory: [],
    
    // 训练结果
    trainingResults: []
  }),

  actions: {
    /**
     * 开始训练
     * @param {object} config - 训练配置
     */
    async startTraining(config) {
      this.isTraining = true
      this.trainingStatus = '正在启动训练任务...'
      this.trainingProgress = 0
      this.currentEpoch = 0
      this.trainingLoss = 0
      this.currentConfig = { ...config }
      
      // 添加到训练历史
      this.trainingHistory.unshift({
        id: Date.now(),
        modelName: config.modelName,
        startTime: new Date().toISOString(),
        status: 'running',
        config: { ...config }
      })
      
      try {
        const result = await window.electronAPI.startTraining(config)
        if (result.success) {
          this.trainingStatus = '训练任务已启动'
          this.simulateTrainingProgress()
        } else {
          this.trainingStatus = `启动失败: ${result.message}`
          this.isTraining = false
          this.updateHistoryStatus('failed')
        }
      } catch (error) {
        console.error('训练启动失败:', error)
        this.trainingStatus = '启动训练时发生错误'
        this.isTraining = false
        this.updateHistoryStatus('failed')
      }
    },

    /**
     * 停止训练
     */
    stopTraining() {
      this.isTraining = false
      this.trainingStatus = '训练已停止'
      this.trainingProgress = 0
      this.currentEpoch = 0
      this.trainingLoss = 0
      this.updateHistoryStatus('stopped')
    },

    /**
     * 模拟训练进度更新
     */
    simulateTrainingProgress() {
      const interval = setInterval(() => {
        if (!this.isTraining) {
          clearInterval(interval)
          return
        }
        
        this.trainingProgress += Math.random() * 5
        if (this.trainingProgress >= 100) {
          this.trainingProgress = 100
          this.trainingStatus = '训练完成'
          this.isTraining = false
          this.updateHistoryStatus('completed')
          clearInterval(interval)
          
          // 添加训练结果
          this.trainingResults.push({
            id: Date.now(),
            modelName: this.currentConfig.modelName,
            completionTime: new Date().toISOString(),
            finalLoss: this.trainingLoss,
            epochs: this.currentConfig.epochs
          })
        } else {
          this.currentEpoch = Math.floor((this.trainingProgress / 100) * this.currentConfig.epochs)
          this.trainingLoss = Math.max(0.1, this.trainingLoss - Math.random() * 0.01)
          this.trainingStatus = `训练中... (${this.currentEpoch}/${this.currentConfig.epochs})`
        }
      }, 1000)
    },

    /**
     * 更新训练历史状态
     * @param {string} status - 状态
     */
    updateHistoryStatus(status) {
      if (this.trainingHistory.length > 0) {
        this.trainingHistory[0].status = status
        this.trainingHistory[0].endTime = new Date().toISOString()
      }
    },

    /**
     * 清除训练历史
     */
    clearHistory() {
      this.trainingHistory = []
      this.trainingResults = []
    }
  },

  getters: {
    /**
     * 获取最近的训练记录
     */
    recentTraining: (state) => {
      return state.trainingHistory[0] || null
    },
    
    /**
     * 获取完成的训练数量
     */
    completedCount: (state) => {
      return state.trainingHistory.filter(h => h.status === 'completed').length
    },
    
    /**
     * 获取失败的训练数量
     */
    failedCount: (state) => {
      return state.trainingHistory.filter(h => h.status === 'failed').length
    }
  }
})
